﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Mail;
using DataLayer;
using BusinessLayer;
using System.Xml;

public partial class Widgets_Mail_Email_send : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      XElement result = new XElement("result");
      XElement Status = new XElement("Status");
      Status.Value = "Permission Denied";
      using (new EntLib.EntTimedLog(Profile.UserName, GetType().ToString(), Request.Form.ToString(), true))
      {
         int TabWidgetID = 0;
         try
         {
            TabWidgetID = Typecast.ToInt32(Request.Form["id"]);
         }
         catch
         {
            TabWidgetID = 0;
         }


         if (TabWidgetID > 0)
         {
            string Action = "";

            try
            {
               Action = Request.QueryString["action"].ToLower();
            }
            catch
            {
            }

            using (var db = DatabaseHelper.GetDashboardData())
            {
               var theTab = (from tw in db.TabWidgets
                             where tw.Id == TabWidgetID
                             select new { tw.Tab.ID, tw.State });
               if (theTab.Count() == 1)
               {
                  //make sure only 1 result is returned, after all, 1 widgetinstance is link to 1 tab
                  var F = new Facade(Functions.GetUserProviderKey(), Profile.UserName);

                  //now confirm user has read permission to this tab
                  var theResult = theTab.Single();

                  if (F.Tab_CheckReadPermission(theResult.ID))
                  {
                     if (theResult.State.Length > 0)
                     {
                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(theResult.State);
                        var Node_State = doc["state"];
                        var UserID = "";
                        try
                        {
                           UserID = Node_State["UserID"].ChildNodes[0].Value;
                        }
                        catch
                        {
                        }

                        var EmailFrom = "";
                        try
                        {
                           EmailFrom = Node_State["EmailFrom"].ChildNodes[0].Value;
                        }
                        catch
                        {
                        }

                        var Password = "";
                        try
                        {
                           Password = Node_State["Enc_Password"].ChildNodes[0].Value;
                        }
                        catch
                        {
                        }

                        var SMTP = "";

                        try
                        {
                           SMTP = Node_State["SMTP"].ChildNodes[0].Value;
                        }
                        catch
                        {
                        }

                        if (UserID.Length > 0 && Password.Length > 0 && SMTP.Length > 0 && EmailFrom.Length > 0)
                        {
                           var SMTP_Secure = Node_State["SMTP_Secure"].ChildNodes[0].Value;
                           var SMTP_Login = Node_State["SMTP_Login"].ChildNodes[0].Value;

                           try
                           {
                              int Port = 0;
                              if (SMTP.IndexOf(":") > 0)
                              {
                                 var idx = SMTP.IndexOf(":");
                                 Port = Typecast.ToInt32(SMTP.Substring(idx + 1));
                                 SMTP = SMTP.Substring(0, idx);
                              }

                              SmtpClient C = new SmtpClient(SMTP);
                              C.EnableSsl = SMTP_Secure == "1";
                              C.DeliveryMethod = SmtpDeliveryMethod.Network;

                              if (Port > 0)
                              {
                                 C.Port = Port;
                              }

                              if (SMTP_Login == "1")
                              {
                                 C.UseDefaultCredentials = false;
                                 C.Credentials = new System.Net.NetworkCredential(UserID, Password);
                              }

                              using (MailMessage M = new MailMessage())
                              {
                                 M.From = new MailAddress(EmailFrom);
                                 M.To.Add(Request.Form["To"]);
                                 M.Subject = Request.Form["Subject"];
                                 M.Body = Request.Form["Body"];
                                 M.IsBodyHtml = false;
                                 C.Send(M);
                              }
                              Status.Value = "Success";
                           }
                           catch (Exception ex)
                           {
                              Status.Value = ex.ToString();
                           }
                        }
                        else
                        {
                           Status.Value = "SMTP Settings insufficient to compose email, click <a href='javascript:void(0)' onclick='$WI(" + TabWidgetID + ").Edit();'>here</a> to configure your smtp settings";
                        }
                     }
                  }
               }
            }
         }
      }
      result.AddFirst(Status);
      Response.Write(result.ToString(SaveOptions.None));
   }
}
